package cn.sytton.taffe.framework.util;

import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.time.*;
import java.util.Date;

/**
 * 日期工具
 *
 * @author skyrock
 */
public class DateUtil {

    private static final String[] PATTERNS = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return DateUtils.parseDate(str.toString(), PATTERNS);
        } catch (ParseException e) {
            return null;
        }
    }


    /**
     * 格式化不同类型的日期对象
     *
     * @param val 被格式化的日期对象, 默认格式 yyyy-MM-dd
     * @return 格式化后的日期字符
     * @dateFormat 格式
     */
    public static String parseDateToStr(Object val, String dateFormat) {
        if (val == null) {
            return "";
        }
        String str;
        if (val instanceof Date) {
            str = cn.hutool.core.date.DateUtil.format((Date) val, dateFormat);
        } else if (val instanceof LocalDateTime) {
            str = cn.hutool.core.date.DateUtil.format(toDate((LocalDateTime) val), dateFormat);
        } else if (val instanceof LocalDate) {
            str = cn.hutool.core.date.DateUtil.format(toDate((LocalDate) val), dateFormat);
        } else {
            str = val.toString();
        }
        return str;
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
}
